#include <pthread.h>
#include <unistd.h>
#include "Sock.hpp"

using namespace ns_sock;

struct ThreadData
{
    int sockfd_;
};

void *Routine(void *args)
{
    pthread_detach(pthread_self());
    ThreadData *ptd=(ThreadData *)(args);
    int sockfd=ptd->sockfd_;

    char buffer[1024];

    while(sockfd)
    {
        int n=recv(sockfd,buffer,sizeof(buffer)-1,0);
        if(n>0)
        {   
            buffer[n]='\0';
            std::cout<<buffer<<std::endl;
        }
        else
        {
            break;
        }

        std::string mgs="server# ";
        mgs+=buffer;
        send(sockfd,mgs.c_str(),mgs.size(),0);
    }

    sleep(30);
    close(sockfd);
    delete ptd;
    return nullptr;
}

int main(int argc,char *argv[],char *env[])
{
    if(argc!=2)
    {
        std::cout<<"Usage:\n"<<argv[0]<<" + "<<"port"<<std::endl;
    }

    uint16_t server_port=atoi(argv[1]);
    Sock sock;

    // 获取套接字
    int listen_sock=sock.Socket();
    // 进行绑定
    sock.Bind(listen_sock,server_port);    
    // 设置监听状态
    sock.Listen(listen_sock);
    
    // 获取链接
    while(true)
    {
        pthread_t tid;

        ThreadData *ptd=new ThreadData;

        ptd->sockfd_=sock.Accept(listen_sock,nullptr,nullptr);

        pthread_create(&tid,nullptr,Routine,(void*)ptd);

        std::cout<<ptd->sockfd_<<" success "<<std::endl;
    }

    return 0;
}